package com.spice.im;


import java.util.ArrayList;






















import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.maxwin.view.XListViewHeader;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;














//import com.example.android.bitmapfun.util.AsyncTask;
import com.beem.push.utils.AsyncTask;
import com.dodola.model.DuitangInfoAdapter;
import com.dodola.model.UnReadMsgNumber;
import com.dodowaterfall.widget.FlowView;
import com.example.android.bitmapfun.util.ObjectCache;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.nostra13.universalimageloader.core.ImageLoader;
//import com.stb.core.pojo.UploadFileRequest;
//import com.speed.im.login.ContactGroup;
import com.speed.im.login.ContactGroupListIQ;
import com.speed.im.login.ContactGroupListIQResponse;
import com.speed.im.login.ContactGroupListIQResponseProvider;
import com.speed.im.login.EncryptionUtil;
import com.spice.im.chat.ChatActivity;
import com.spice.im.chat.ChatPullRefListActivity;
import com.spice.im.chat.LoadingDialog;
import com.spice.im.friend.FriendAddIQ;
import com.spice.im.friend.FriendAddIQResponse;
import com.spice.im.friend.FriendAddIQResponseProvider;
import com.spice.im.friend.SearchIQ;
import com.spice.im.friend.SearchIQResponse;
import com.spice.im.friend.SearchIQResponseProvider;
import com.spice.im.group.GroupDetailsActivity;
import com.spice.im.profile.UpProfileIQ;
import com.spice.im.profile.UpProfileIQProvider;
import com.spice.im.profile.UpProfileIQResponse;
import com.spice.im.profile.UpProfileIQResponseProvider;
import com.spice.im.ui.BadgeView;
import com.spice.im.ui.CustomListView;
import com.spice.im.ui.HandyTextView;
import com.spice.im.ui.CustomListView.OnLoadMoreListener;
import com.spice.im.ui.CustomListView.OnRefreshListener;
import com.spice.im.utils.ConstantValues;
import com.spice.im.utils.DialogUtil;
import com.spice.im.utils.Feed;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.ImageFetcher;
import com.spice.im.utils.MyDialog;
import com.spice.im.utils.MyDialogPopWinGroup;
import com.spice.im.utils.MyDialogPopWinProfile;
import com.spice.im.utils.TextUtils;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onMiddleImageButtonClickListener;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;
import com.spice.im.utils.SwitcherButton.onSwitcherButtonClickListener;
import com.stb.core.chat.BeemChatManager;
import com.stb.core.chat.ContactGroup;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.IConnectionStatusCallback;
//import com.stb.isharemessage.service.Contact;
import com.stb.isharemessage.service.XmppConnectionAdapter;
import com.stb.isharemessage.service.aidl.IChat;
import com.stb.isharemessage.service.aidl.IChatManager;
import com.stb.isharemessage.service.aidl.IChatManagerListener;
import com.stb.isharemessage.service.aidl.IMessageListener;
import com.stb.isharemessage.service.aidl.IRoster;
import com.stb.isharemessage.service.aidl.IXmppFacade;
import com.stb.isharemessage.service.aidl.IBeemRosterListener;
import com.stb.isharemessage.ui.feed.DynamicsIQ;
import com.stb.isharemessage.ui.feed.DynamicsIQResponse;
import com.stb.isharemessage.ui.feed.DynamicsIQResponseProvider;
import com.stb.isharemessage.ui.feed.DynamicsItem;
import com.stb.isharemessage.ui.feed.OtherFeedListActivity;
import com.stb.isharemessage.utils.BeemConnectivity;
//import com.test.HandyTextView;
//import com.test.MainActivity;
//import com.test.R;

//import dalvik.system.VMRuntime;














import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentTransaction;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ext.SatelliteMenu;
import android.view.ext.SatelliteMenuItem;
import android.view.ext.SatelliteMenu.SateliteClickedListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.RecyclerListener;
import android.widget.AdapterView.OnItemClickListener;

import com.spice.im.utils.SwitcherButton.SwitcherButtonState;

import android.widget.ListView;
public class OtherProfileActivity extends Activity implements IConnectionStatusCallback,OnClickListener{
	private View mNetErrorView;
	private TextView mConnect_status_info;
	private ImageView mConnect_status_btn;
	private Context mContext;
    private exPhoneCallListener myPhoneCallListener = null;
    private TelephonyManager tm = null;
	
    private final static float TARGET_HEAP_UTILIZATION = 0.75f;
    private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;
    private static final Intent SERVICE_INTENT = new Intent();
	static {
		//pkg,cls
//		SERVICE_INTENT.setComponent(new ComponentName("com.test", "com.stb.isharemessage.BeemService"));
//		SERVICE_INTENT.setComponent(new ComponentName("com.stb.isharemessage", "com.stb.isharemessage.BeemService"));
		SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));//自身应用pkg名称，非service所在pkg名称
	}
	private static ExecutorService LIMITED_TASK_EXECUTOR;
    static {
    	LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7); 
    }; 
    protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
	}

	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}
	private final ServiceConnection mServConn = new BeemServiceConnection();
    private boolean mBinded = false;
    private IXmppFacade mXmppFacade;
    protected FlippingLoadingDialog mLoadingDialog;
    private HeaderLayout mHeaderLayout;
//    private XListViewHeader xListViewHeader;
    private ImageFetcher mImageFetcher;
	private int itemWidth;
	private int column_count = 3;// 显示列数 just for image cut
//	protected void showLoadingDialog(String text) {
//		if (text != null) {
//			mLoadingDialog.setText(text);
//		}
//		mLoadingDialog.show();
//	}
//
//	protected void dismissLoadingDialog() {
//		if (mLoadingDialog.isShowing()) {
//			mLoadingDialog.dismiss();
//		}
//	}
    
	protected void showLoadingDialog() {
		findViewById(R.id.pb).setVisibility(View.VISIBLE);	
	}

	protected void dismissLoadingDialog() {
		findViewById(R.id.pb).setVisibility(View.GONE);
	}
	
//	private Button btn;
	private final OkListener mOkListener = new OkListener();
//	private TextView udidTextView;
    //----------------------版块滑动部分数据---------------------------//
    private int screenWidth;//屏幕的宽度
	private int imgWidth;   // 图片宽度
	private int currentView=0;// 当前视图
	private int viewOffset;// 动画图片偏移量
	
	//----------------------刷新部分数据----------------------------//
	private static final int LOAD_DATA_FINISH = 10;
	private static final int REFRESH_DATA_FINISH = 11;
//	private CustomListAdapter mAdapter;
//	private CustomListView mListView;
//	private PullToRefreshListView ptrlv = null;
	
//	private final ContactGroupListOnClick mOnContactClick = new ContactGroupListOnClick();/**单击某联系人，打开chat聊天对话框*/
	
//	private LinkedList<ContactGroup> tempList;
//	private Map<View,CustomListAdapter> maps=new HashMap<View, CustomListAdapter>();
//	private Map<View,CustomListView> mapList=new HashMap<View, CustomListView>();
	
//	private EditText editInput_search;
	
	private DuitangInfoAdapter duitangInfoAdapter = null;//用户信息存入本地数据库
	private String jid = "";
	private BaseDialog mBaseDialog;
	private EditTextDialog mEditTextDialog;
	
	private String searchkey;
	private String CurrentUid;
	
	private String CurrentName;
	private String CurrentNote;
	private String CurrentSex;
	private String CurrentBirthyear;
	private String CurrentBirthmonth;
	private String CurrentBirthday;
//	private String OtherUid;//fuid
	
	
	private LinearLayout mLayoutChat;// 对话
	private LinearLayout mLayoutReport;// 拉黑/举报
	private LinearLayout mLayoutInvite;//添加好友
	 
	
	private RelativeLayout mLayoutFeed;// 状态根布局
	private LinearLayout mLayoutFeedPicture;// 状态图片布局
	private ImageView mRivFeedPicture;// 状态图片
	private EmoticonsTextView mHtvFeedSignature;// 状态签名
	private HandyTextView mHtvFeedDistance;// 状态距离
	
	private RelativeLayout user_item_relative;//基本信息根布局
	private FlowView imageView;//头像
	private HandyTextView contentView;//昵称
//    TextView timeView;
    
    LinearLayout user_item_layout_gender;//20140731 added
    ImageView user_item_iv_gender;//性别
    HandyTextView user_item_htv_age;//年龄
    
    HandyTextView user_item_htv_account;//帐号
    HandyTextView user_item_htv_sign;//个性签名
    
    ImageView user_item_iv_icon_group_role;//是否群组
    
    BadgeView badgeView;//未读消息气泡
    TextView unreadmsgnumber;//未读消息数量
    HandyTextView account_gone;
    RelativeLayout otherprofile_layout_sex_sign;
    LinearLayout otherprofile_bottom;
    private LoadingDialog loadingDialog;
    
    Dialog dialog3 = null;
    
    public void onCreate(Bundle savedInstanceState) {
//    	VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);
//    	VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); //设置最小heap内存为6MB大小。当然对于内存吃紧来说还可以通过手动干涉GC去处理
    	requestWindowFeature(Window.FEATURE_NO_TITLE);
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.activity_otherprofile);
    	mLoadingDialog = new FlippingLoadingDialog(this, "请求提交中");
    	
		mHeaderLayout = (HeaderLayout) findViewById(R.id.otherprofile_header);
//		mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
//		mHeaderLayout.setTitleRightImageButton("联系人列表", null,
//				R.drawable.refresh2,
//				new OnRightImageButtonClickListener());
		
		
		mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
		mHeaderLayout.setTitleRightImageButton("搜索结果", null,
				R.drawable.return2,
				new OnRightImageButtonClickListener());
//		mHeaderLayout.init(HeaderStyle.TITLE_CHAT);
//		mHeaderLayout.setTitleChat(R.drawable.ic_chat_dis_1,
//				R.drawable.bg_chat_dis_active, "搜索结果",
//				"",
//				R.drawable.ic_menu_invite,//ic_menu_invite  ic_topbar_profile
//				new OnMiddleImageButtonClickListener(),
//				R.drawable.return2,
//				new OnRightImageButtonClickListener());
		
		mLayoutChat = (LinearLayout) findViewById(R.id.otherprofile_bottom_layout_chat);
		mLayoutReport = (LinearLayout) findViewById(R.id.otherprofile_bottom_layout_report);
		mLayoutInvite = (LinearLayout) findViewById(R.id.otherprofile_bottom_layout_invite);
		
		mLayoutChat.setOnClickListener(this);
		mLayoutReport.setOnClickListener(this);
		mLayoutInvite.setOnClickListener(this);
		
		mLayoutFeed = (RelativeLayout) findViewById(R.id.otherprofile_layout_feed);//feed所在模块
		mLayoutFeedPicture = (LinearLayout) findViewById(R.id.otherprofile_layout_feed_pic);//图片所在LinearLayout
		mRivFeedPicture = (ImageView) findViewById(R.id.otherprofile_riv_feed_pic);//图片所在ImageView
		mHtvFeedSignature = (EmoticonsTextView) findViewById(R.id.otherprofile_htv_feed_sign);//动态详情EmoticonsTextView
		mHtvFeedDistance = (HandyTextView) findViewById(R.id.otherprofile_htv_feed_distance);//HandyTextView距离详情
		mLayoutFeed.setOnClickListener(this);
		
		imageView = (FlowView)findViewById(R.id.news_pic);
		contentView = (HandyTextView) findViewById(R.id.user_item_htv_name);//昵称
        user_item_layout_gender = (LinearLayout)findViewById(R.id.user_item_layout_gender);
        user_item_iv_gender = (ImageView)findViewById(R.id.user_item_iv_gender);
        user_item_htv_age = (HandyTextView)findViewById(R.id.user_item_htv_age);
        
        user_item_htv_account = (HandyTextView)findViewById(R.id.user_item_htv_account);//帐号
        user_item_htv_sign = (HandyTextView)findViewById(R.id.user_item_htv_sign);//个性签名
        user_item_iv_icon_group_role = (ImageView)findViewById(R.id.user_item_iv_icon_group_role);
        user_item_relative = (RelativeLayout)findViewById(R.id.user_item_relative);
        account_gone = (HandyTextView)findViewById(R.id.account_gone);
        otherprofile_layout_sex_sign = (RelativeLayout)findViewById(R.id.otherprofile_layout_sex_sign);
        otherprofile_bottom = (LinearLayout)findViewById(R.id.otherprofile_bottom);
        
        
        user_item_relative.setOnClickListener(this);
        
        loadingDialog = new LoadingDialog(this);
//        badgeView = new BadgeView(mContext, user_item_relative);
//        unreadmsgnumber = (TextView)findViewById(R.id.unreadmsgnumber);
//        xListViewHeader = (XListViewHeader)findViewById(R.id.xlistview_header);
//        xListViewHeader.setVisiableHeight(60);
//        xListViewHeader.setState(0);
//        xListViewHeader.setVisibility(View.VISIBLE);
        
        
        mImageFetcher = new ImageFetcher(this, 240);
        mImageFetcher.setUListype(0);////0普通图片listview 1瀑布流  2地图模式
        mImageFetcher.setLoadingImage(R.drawable.empty_photo);
        
        itemWidth = this.getWindowManager().getDefaultDisplay().getWidth() / column_count;// 根据屏幕大小计算每列宽度
        
//        editInput_search = (EditText)findViewById(R.id.editInput_search);
//        editInput_search.addTextChangedListener(new watcher());
        
//        initRefreshView(linkedList);
		
//    	btn = (Button)findViewById(R.id.button1);
//        btn.setOnClickListener(mOkListener);
//        udidTextView = (TextView)findViewById(R.id.udid_name);
        mContext = this;
        mNetErrorView = findViewById(R.id.net_status_bar_top);
        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
        mConnect_status_btn.setOnClickListener(this);
        
	    IntentFilter mFilter = new IntentFilter();
	    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
	    registerReceiver(mNetWorkReceiver, mFilter);
	    
	    searchkey = getIntent().getStringExtra("searchkey");
	    if(searchkey==null || searchkey.equalsIgnoreCase("null"))
	    	searchkey = "";
        /* 添加自己实现的PhoneStateListener */
        myPhoneCallListener = new exPhoneCallListener();
       
       /* 取得电话服务 */
        tm =(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
       
        /* 注册电话通信Listener */
        tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_CALL_STATE);
        
        duitangInfoAdapter = DuitangInfoAdapter.getInstance(this);
        SpiceApplication.getInstance().addActivity(this);
    	
//    	ObjectCache.saveStatus("isConnected", true, this);//标识为手动启动
    }
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			//网络设置
			case R.id.net_status_bar_btn:
				setNetworkMethod(this);
			    break;
			case R.id.otherprofile_bottom_layout_chat:
				Intent intent = new Intent(OtherProfileActivity.this,ChatPullRefListActivity.class);
				intent.putExtra("jid", fuid+"@0");
				startActivity(intent);
				break;
			case R.id.otherprofile_bottom_layout_report:
//				rePort();
//				System.out.println("拉黑/举报");
				showCustomToast("功能建设中...");
				break;
			case R.id.otherprofile_bottom_layout_invite:
				mEditTextDialog = new EditTextDialog(mContext);
				mEditTextDialog.setTitle("添加好友,填写备注留言");
				mEditTextDialog.setButton("取消",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								mEditTextDialog.cancel();
							}
						}, "确认", new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								String text = mEditTextDialog.getText();
								if (text == null) {
									mEditTextDialog.requestFocus();
									showCustomToast("请输入发送给对方的备注留言");
								} else {
									mEditTextDialog.dismiss();
//									showCustomToast("您输入的备注留言为:" + text);
									addFriendRequest(fuid,text);
								}
							}
						});
				mEditTextDialog.show();
				break;
			case R.id.otherprofile_layout_feed:
				intent = new Intent(OtherProfileActivity.this,
						OtherFeedListActivity.class);
//				intent.putExtra("entity_profile", mProfile);
//				intent.putExtra("entity_people", mPeople);
				intent.putExtra("otherusername", fuid);//StringUtils.parseName(JIDWithRes)
//				intent.putExtra("mFrom", "2");
//				intent.putExtra("roomname", roomname);
//	        	intent.putExtra("nickname", nickname);
//	        	intent.putExtra("name", name);
//	        	intent.putExtra("headimg", headimg);
//	        	intent.putExtra("myheadimg", myheadimg);
//	        	intent.putExtra("myusername", myusername);
//	        	intent.putExtra("myjid", myjid);
				startActivity(intent);
				break;	
			case R.id.user_item_relative:
				if(dialog3!=null)
					dialog3.dismiss();
				dialog3 =null;		
				dialog3 = DialogUtil.getMyDialogPopWinProfile("修改个人资料",
								"",//请选择考勤班段
								OtherProfileActivity.this, new MyDialogPopWinProfile.MyDialogListener() {
									
									@Override
									public void onPositiveClick(Dialog dialog, View view) {
										((MyDialogPopWinProfile)dialog3).validate();
										
									    String name = null;
									    String gender = null;//默认0未知，1男，2女
									    String usersign = null;
									    String birthdayfull = null;
									    String birthyear = null;
									    String birthmonth = null;
									    String birthday = null;
										if(((MyDialogPopWinProfile)dialog3).getName()!=null 
												&& ((MyDialogPopWinProfile)dialog3).getName().length()!=0
												&& !((MyDialogPopWinProfile)dialog3).getName().equalsIgnoreCase("null")){
											name = ((MyDialogPopWinProfile)dialog3).getName();
										}else{
											
												showCustomToast("名称不能为空!");
												return;
										}
										if(((MyDialogPopWinProfile)dialog3).getGender()!=null 
												&& ((MyDialogPopWinProfile)dialog3).getGender().length()!=0
												&& !((MyDialogPopWinProfile)dialog3).getGender().equalsIgnoreCase("null")){
											gender = ((MyDialogPopWinProfile)dialog3).getGender();
										}else{
											
												showCustomToast("性别不能为空!");
												return;
										}
										if(((MyDialogPopWinProfile)dialog3).getUsersign()!=null 
												&& ((MyDialogPopWinProfile)dialog3).getUsersign().length()!=0
												&& !((MyDialogPopWinProfile)dialog3).getUsersign().equalsIgnoreCase("null")){
											usersign = ((MyDialogPopWinProfile)dialog3).getUsersign();
										}else{
											
												showCustomToast("个性签名不能为空!");
												return;
										}
										if(((MyDialogPopWinProfile)dialog3).getBirthyear()!=null 
												&& ((MyDialogPopWinProfile)dialog3).getBirthyear().length()!=0
												&& !((MyDialogPopWinProfile)dialog3).getBirthyear().equalsIgnoreCase("null")){
											birthyear = ((MyDialogPopWinProfile)dialog3).getBirthyear();
										}else{
											
												showCustomToast("出生年月日不能为空!");
												return;
										}
										if(((MyDialogPopWinProfile)dialog3).getBirthmonth()!=null 
												&& ((MyDialogPopWinProfile)dialog3).getBirthmonth().length()!=0
												&& !((MyDialogPopWinProfile)dialog3).getBirthmonth().equalsIgnoreCase("null")){
											birthmonth = ((MyDialogPopWinProfile)dialog3).getBirthmonth();
										}else{
											
												showCustomToast("出生年月日不能为空!");
												return;
										}
										if(((MyDialogPopWinProfile)dialog3).getBirthday()!=null 
												&& ((MyDialogPopWinProfile)dialog3).getBirthday().length()!=0
												&& !((MyDialogPopWinProfile)dialog3).getBirthday().equalsIgnoreCase("null")){
											birthday = ((MyDialogPopWinProfile)dialog3).getBirthday();
										}else{
											
												showCustomToast("出生年月日不能为空!");
												return;
										}
											//Toast.makeText(GroupDetailsActivity.this, "PositiveClick!photo="+photo, Toast.LENGTH_SHORT).show();
										if(CurrentUid.equals(fuid)){
											dialog3.dismiss();
											updateProfileRequest(name,
													gender,///默认0未知，1男，2女
													usersign,
													birthyear,
													birthmonth,
													birthday);
										}else{
											dialog3.dismiss();
											showCustomToast("只能由本人修改自身资料信息!");
										}	
										
									}
									
									@Override
									public void onNegativeClick(Dialog dialog, View view) {

//											Toast.makeText(GroupDetailsActivity.this, "NegativeClick!", Toast.LENGTH_SHORT).show();
											dialog3.dismiss();
										
									}
								}, MyDialog.ButtonBoth,CurrentUid,fuid,CurrentName,
								CurrentNote,
								CurrentSex,
								CurrentBirthyear,
								CurrentBirthmonth,
								CurrentBirthday);
				dialog3.show();
				break;
		}
	}
    @Override
    protected void onResume() {
    	Log.e("================20170507 MainListActivity onResume================", "+++++++onResume+++++++");
		super.onResume();
		isWork = false;
        if(BeemConnectivity.isConnected(this)){
        	mNetErrorView.setVisibility(View.GONE);
        }else{
        	mNetErrorView.setVisibility(View.VISIBLE);
        }
		if (!mBinded){
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);	    
		}
		mImageFetcher.setExitTasksEarly(false);
		Log.e("================20170507 MainListActivity onResume 1111================", "+++++++onResume+++++++jid="+jid);
        if(jid!=null
        		&& jid.length()!=0
        		&& !jid.equalsIgnoreCase("null")){
        	Log.e("================20170507 MainListActivity onResume 2222================", "+++++++onResume+++++++jid="+jid);
//        	//通知ContactListPullRefListActivity更新局部 消息图章为0，不显示消息图章
//        	try{
//    		    int index = mAdapter.containsKey(StringUtils.parseBareAddress(jid));
//    		    Log.e("※※※※※####20170507MainListActivity####※※※※※", "※※index="+index);
//    		    if(index!=-1){
//    		    	updateUi4ptrlv((index+1),StringUtils.parseBareAddress(jid),true);
//    		    }
//        	}catch(Exception e){
//        		e.printStackTrace();
//        	}
        	// 下拉刷新:更新局部 消息图章,从其他页面比如ChatActivity返回本页面时
    		getContactList(ConstantValues.refresh);
        }
//		// 下拉刷新:更新局部 消息图章,从其他页面比如ChatActivity返回本页面时
//		getContactList(ConstantValues.refresh);
    }
    //SingleTask用此方法处理传过来的参数
    @Override
    protected void onNewIntent(Intent intent) {
    	Log.e("================20170507 MainListActivity onNewIntent================", "+++++++onNewIntent+++++++");
            super.onNewIntent(intent);

	        mImageFetcher.setExitTasksEarly(false);
            
            jid = intent.getStringExtra("jid");
            
            Log.e("================20170507 MainListActivity onNewIntent================", "+++++++onNewIntent+++++++jid="+jid); 
    }
    public void onPause() {
    	super.onPause();
    	mImageFetcher.setExitTasksEarly(true);
    	Log.e("================2015 TestActivity.java ================", "++++++++++++++onPause()++++++++++++++mBinded="+mBinded);
//		if (mBinded) {
//			unbindService(mServConn);
//			mBinded = false;
//		}
    }
    /**
     * 重写finish()方法
     */
    @Override
    public void finish() {
        super.finish(); //记住不要执行此句
//        moveTaskToBack(true); //设置该activity永不过期，即不执行onDestroy()
    }   
 
//    public void finishNew() {
//        super.finish(); //记住要执行此句
//        moveTaskToBack(false);
//    }
    @Override
    protected void onDestroy() {
		super.onDestroy();
		Log.e("================2015 TestActivity.java ================", "++++++++++++++onDestroy()000++++++++++++++mBinded="+mBinded);
		mImageFetcher.onCancel();
		clearAsyncTask();
    	Log.e("================2015 TestActivity.java ================", "++++++++++++++onDestroy()111++++++++++++++");
// 	    XmppConnectionAdapter.isPause = true;
//		if(XmppConnectionAdapter.instance!=null)
//			XmppConnectionAdapter.instance.resetApplication();
//		XmppConnectionAdapter.instance = null;
//		stopService(SERVICE_INTENT);
		Log.e("================2015 TestActivity.java ================", "++++++++++++++onDestroy()222++++++++++++++");
//		loadingView.isStop = true;
		
	    try{
		    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
		    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
	    }catch (RemoteException e) {
	    	e.printStackTrace();
	    }
		if (mBinded) {
			getApplicationContext().unbindService(mServConn);
		    mBinded = false;
		}

		mXmppFacade = null;
		unregisterReceiver(mNetWorkReceiver); // 删除广播
		if(tm!=null){
			tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_NONE);//取消监听即可
			tm = null;
		}
		if(myPhoneCallListener!=null)
			myPhoneCallListener = null;
		
//		SpiceApplication.getInstance().exit();
		Log.e("================2015 TestActivity.java ================", "++++++++++++++onDestroy()333++++++++++++++");
    }
    /**
     * The service connection used to connect to the Beem service.
     */
    private class BeemServiceConnection implements ServiceConnection {
		/**
		 * Constructor.
		 */
		public BeemServiceConnection() {
		}
	
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
		    	mBinded = true;
		    	try{
		    		mXmppFacade.getXmppConnectionAdapter().registerConnectionStatusCallback(OtherProfileActivity.this);
		    		CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
//		    		CurrentName = mXmppFacade.getXmppConnectionAdapter().getName();
		    	}catch(Exception e){
		    		e.printStackTrace();
		    	}
//		    	getContactList();
//		    	getData(0);
		    	getContactList(0);
		    }
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
		    try{
			    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
			    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
		    }catch (RemoteException e) {
		    	e.printStackTrace();
		    }
		    mXmppFacade = null;
		    mBinded = false;
		}
    }
//    private List<Contact> mListContact;
//    private LinkedList linkedList = new LinkedList();
    private HashMap linkedList = new HashMap();
    private String fuid = "";
    private String isfriend;//true 或 false
//	private String searchkey = "雷敏";
	private String searchtype = "0";
	private String ages = "12";
	private String genders = "1";
	private String distances = "5000";
	private String online = "0";
	private String[] errorMsg = new String[]{"抱歉,没有找到相关结果.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"",
			"请求异常,稍候重试!"};
	private int errorType = 5;
    private int currentPage = 0;
    private int numberresult = 50;
    private HashMap UnReadMsgNumberMap = new HashMap();
	public boolean initContactList(){
		Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()111++++++++++++++");
		UnReadMsgNumberMap.clear();
		if(BeemConnectivity.isConnected( getApplicationContext())){
			Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()222++++++++++++++");
		    try {
		    	if(mXmppFacade!=null){
		    		Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()333++++++++++++++");
			    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
			    			){
			    		
			    		SearchIQ reqXML = new SearchIQ();
			            reqXML.setId("1234567890");
			            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
			            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
			            reqXML.setSearchkey(searchkey);//searchkey
			            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
					    String login = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
			            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,login);
			            reqXML.setUuid(uuid);
//			            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
			            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid;
			            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
			            reqXML.setHashcode(hash_dest);
			            reqXML.setType(IQ.Type.SET);
			            String elementName = "searchiq"; 
			    		String namespace = "com:isharemessage:searchiq";
			    		SearchIQResponseProvider provider = new SearchIQResponseProvider();
			            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "searchiq", "com:isharemessage:searchiq", provider);
			            
			            if(rt!=null){
			                if (rt instanceof SearchIQResponse) {
			                	final SearchIQResponse searchIQResponse = (SearchIQResponse) rt;

			                    if (searchIQResponse.getChildElementXML().contains(
			                            "com:isharemessage:searchiq")) {
//			    					MainActivity.this.runOnUiThread(new Runnable() {
//				                    	
//            							@Override
//            							public void run() {
//            								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
//            							}
//            						});
			                        String Id = searchIQResponse.getId();
			                        String Apikey = searchIQResponse.getApikey();
			                        HashMap cGroups = searchIQResponse.getCGroups();
			                        if(cGroups.size()!=0){
//				                        linkedList = new LinkedList(cGroups);
			                        	linkedList = cGroups;
//			                        	for(int q=0;q<cGroups.size();q++){
//			                        		linkedList.add(cGroups.get(q));
//			                        	}
			                        	Iterator iter = linkedList.entrySet().iterator();
			                        	Map.Entry entry = null;
			            				Object key = null;
			            				Object val = null;
			            				ContactGroup detail = null;
			            				while (iter.hasNext()) {
			            	    			entry = (Map.Entry) iter.next();
			            	    			key = entry.getKey();
			            	    			val = entry.getValue();
			            	    			detail = (ContactGroup)val;
			            	    			fuid = StringUtils.parseBareAddress2(detail.getJID());
			            	    			CurrentName = detail.getName();
			            	    			CurrentNote = detail.getNote();
			            	    			CurrentSex = detail.getSex()+"";
			            	    			CurrentBirthyear = detail.getBirthyear();
			            	    			CurrentBirthmonth = detail.getBirthmonth();
			            	    			CurrentBirthday = detail.getBirthday();
			            	    			isfriend = key+"";
			            				}
			                        	
				                        Log.e("响应packet结果解析...............", "Id="+Id+";Apikey="+Apikey); 
	//			                        mListContact = new ArrayList<Contact>(); 
	//			                        for(int k=0;k<cGroups.size();k++){
	//			                        	Log.e("响应packet结果解析...............", "cGroups"); 
	////			                        	mListContact.add(contact);
	//			                        }
				                        cGroups = null;
				                        return true;
			                        }
			                    }
			                } 
			            }
			    		
			    		
			    		Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()444++++++++++++++");

			    	    if(linkedList!=null && linkedList.size()!=0)
			    	    	errorType = 5;
			    	    else{
			    	    	if(linkedList!=null && linkedList.size()==0)
			    	    		errorType = 0;
			    	    	else
			    	    		errorType = 6;
			    	    }
						mBinded = true;//20130804 added by allen
			    	}else
			    		errorType = 1;
		    	}else
		    		errorType = 2;
				
		    } catch (RemoteException e) {
		    	errorType = 3;
		    	e.printStackTrace();
		    	
		    } catch (Exception e){
		    	errorType = 3;
		    	e.printStackTrace();
		    }
	    }else{
	    	errorType = 4;
	    }
		return false;
	}
	private boolean flag = false;
//	private boolean isWork = false;
	private void getContactList(final int type) {
//		private View view2;
//		private int type2;
		if(!isWork){
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
//				showLoadingDialog("正在加载,请稍后...");
//				showLoadingDialog();
				loadingDialog.show();
//				if(type==0){
//					showLoadingDialog();
//				}
				if(flag || (type==0)){
////					showLoadingDialog("正在加载,请稍后...");
//					xListViewHeader.setShowText("正在加载,请稍候...");
//					xListViewHeader.setVisibility(View.VISIBLE);
//					xListViewHeader.setState(2);
				}
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				initContactList();
				InitialFeeds(fuid);
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
//				dismissLoadingDialog();
				loadingDialog.dismiss();
//				if(type==0){
////					   view.findViewById(R.id.pb).setVisibility(View.GONE);
//					dismissLoadingDialog();
//				}
//				if(flag || (type==0)){
//					xListViewHeader.setState(0);
//					xListViewHeader.setVisibility(View.GONE);
//				}
//				if (!result) {
//					showCustomToast("数据加载失败...");
//					mHandler2.sendEmptyMessage(3);
//				} else {
//					mHandler2.sendEmptyMessage(0);
//				}
				if (result) {	
					mHandler.sendEmptyMessage(1);
//					parserJsonData(result,type,view);
//					initRefreshView(linkedList);
//					parserData(type);
//					getData(2);
//					Message load = mHandler.obtainMessage(LOAD_DATA_FINISH, linkedList);
//					mHandler.sendMessage(load);
					
//					Message refresh = mHandler.obtainMessage(REFRESH_DATA_FINISH,
//							tempList);
//					mHandler.sendMessage(refresh);
				}else{
					//提示没有获取到数据：可能网络问题
					mHandler.sendEmptyMessage(0);
				}
//				if(type==0){
//				   view.findViewById(R.id.pb).setVisibility(View.GONE);
//				}
				if(flag || (type==0)){
//					xListViewHeader.setState(0);
//					xListViewHeader.setVisibility(View.GONE);
				}
				flag = false;
				isWork = false;
			}

		});
		isWork = true;
		}
	}
	
	
	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(OtherProfileActivity.this).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(OtherProfileActivity.this);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
//	Handler mHandler2 = new Handler() {
//
//		@Override
//		public void handleMessage(android.os.Message msg) {
//			super.handleMessage(msg);
//			switch (msg.what) {
//			case 0:
//				if(errorType==5 && linkedList!=null){
//					Contact contact = null;
//			        for (int i = 0; i < linkedList.size(); i++) {
//			        	contact = (Contact)mListContact.get(i);
//			        	Log.e("MMMMMMMMMMMM20140714(2)MMMMMMMMMMMM", "++++++++++++++"+contact.toString()+"++++++++++++");
//			        }
//				}else{
//		        	showCustomToast(errorMsg[errorType]);
//		        }
//				break;
//
//			case 1:
//				
//				showCustomToast("已达顶端!");
//				break;
//			case 2:
//				
//				showCustomToast("已达底端!");
//				break;
//			default:
//				
//				break;
//			}
//		}
//
//	};
    private class OkListener implements OnClickListener {
    	
		/**
		 * Constructor.
		 */
		public OkListener() { }
	
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.button1:
//				getContactList();
//				getData(0);
				getContactList(0);
				break;
			default:
				break;
			}
		}
    };
    
	@Override
	public void connectionStatusChanged(int connectedState, String reason) {
		Log.e("MMMMM20140604MMMMMMMMMMMM", "++++++++++++++connectionStatusChanged0++++++++++++");
		switch (connectedState) {
		case 0://connectionClosed
			mHandler3.sendEmptyMessage(0);
			break;
		case 1://connectionClosedOnError
//			mConnectErrorView.setVisibility(View.VISIBLE);
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("连接异常!");
			mHandler3.sendEmptyMessage(1);
			break;
		case 2://reconnectingIn
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("连接中...");
			mHandler3.sendEmptyMessage(2);
			break;
		case 3://reconnectionFailed
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("重连失败!");
			mHandler3.sendEmptyMessage(3);
			break;
		case 4://reconnectionSuccessful
//			mNetErrorView.setVisibility(View.GONE);
			mHandler3.sendEmptyMessage(4);

		default:
			break;
		}
	}
	Handler mHandler3 = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				break;

			case 1:
				mNetErrorView.setVisibility(View.VISIBLE);
				if(BeemConnectivity.isConnected(mContext))
				mConnect_status_info.setText("连接异常!");
				break;

			case 2:
				mNetErrorView.setVisibility(View.VISIBLE);
				if(BeemConnectivity.isConnected(mContext))
				mConnect_status_info.setText("连接中...");
				break;
			case 3:
				mNetErrorView.setVisibility(View.VISIBLE);
				if(BeemConnectivity.isConnected(mContext))
				mConnect_status_info.setText("重连失败!");
				break;
				
			case 4:
				mNetErrorView.setVisibility(View.GONE);
				String udid = "";
				String partnerid = "";
				try{
					udid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().UDID;
					partnerid = mXmppFacade.getXmppConnectionAdapter().getMService().getPartnerid();
				}catch(Exception e){
					e.printStackTrace();
				}
//				udidTextView.setText("udid="+udid);
//				partneridEditText.setText(partnerid);
//				getContactList();//20141025 added by allen
				break;
			case 5:
				mNetErrorView.setVisibility(View.VISIBLE);
				mConnect_status_info.setText("当前网络不可用，请检查你的网络设置。");
				break;
			case 6:
				if(mXmppFacade!=null 
//						&& mXmppFacade.getXmppConnectionAdapter()!=null 
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
						&& BeemConnectivity.isConnected(mContext)){
					
				}else{
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("网络可用,连接中...");
				}
				break;	
			case 12:
				
				break;	
			}
		}

	};
	private BroadcastReceiver mNetWorkReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();  
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  
                Log.d("PoupWindowContactList", "网络状态已经改变");  
//                connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
//                info = connectivityManager.getActiveNetworkInfo();    
//                if(info != null && info.isAvailable()) {  
//                    String name = info.getTypeName();  
//                    Log.d(tag, "当前网络名称：" + name);  
//                    //doSomething()  
//                } else {  
//                    Log.d(tag, "没有可用网络");  
//                  //doSomething()  
//                }  
                if(BeemConnectivity.isConnected(context)){
//                	mNetErrorView.setVisibility(View.GONE);
//                	isconnect = 0;
                	mHandler3.sendEmptyMessage(6);//4
                }else{
//                	mNetErrorView.setVisibility(View.VISIBLE);
//                	isconnect = 1;
                	mHandler3.sendEmptyMessage(5);
                	Log.d("PoupWindowContactList", "当前网络不可用，请检查你的网络设置。");
                }
            } 
        }
	};
	
	private boolean phonestate = false;//false其他， true接起电话或电话进行时 
    /* 内部class继承PhoneStateListener */
    public class exPhoneCallListener extends PhoneStateListener
    {
        /* 重写onCallStateChanged
        当状态改变时改变myTextView1的文字及颜色 */
        public void onCallStateChanged(int state, String incomingNumber)
        {
          switch (state)
          {
            /* 无任何状态时 :说明没有拨打电话的界面的时候，也就是在拨打电话前和挂电话后的情况*/
            case TelephonyManager.CALL_STATE_IDLE:
            	Log.e("================20131216 无任何电话状态时================", "无任何电话状态时");
            	if(phonestate){
            		onPhoneStateResume();
            	}
            	phonestate = false;
              break;
            /* 接起电话时 :至少有一个电话存在、拨出或激活、接听，而没有一个电话在通话或等待的状态*/
            case TelephonyManager.CALL_STATE_OFFHOOK:
            	Log.e("================20131216 接起电话时================", "接起电话时");
            	onPhoneStatePause();
            	phonestate = true;
              break;
            /* 电话进来时 :在通话的过程中*/
            case TelephonyManager.CALL_STATE_RINGING:
//              getContactPeople(incomingNumber);
            	Log.e("================20131216 电话进来时================", "电话进来时");
//            	onBackPressed();
            	onPhoneStatePause();
            	phonestate = true;
              break;
            default:
              break;
          }
          super.onCallStateChanged(state, incomingNumber);
        }
    }
    
    protected void onPhoneStatePause() {
//		super.onPause();
    	try{
			if (mBinded) {
				getApplicationContext().unbindService(mServConn);
			    mBinded = false;
			}
			mXmppFacade = null;
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    protected void onPhoneStateResume() {
//		super.onResume();
    	try{
		if (!mBinded){
//		    new Thread()
//		    {
//		        @Override
//		        public void run()
//		        {
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);

//		        }
//		    }.start();		    
		}
		if (mBinded){
			mImageFetcher.setExitTasksEarly(false);
		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    /*
     * 打开设置网络界面
     * */
    public static void setNetworkMethod(final Context context){
        //提示对话框
        AlertDialog.Builder builder=new AlertDialog.Builder(context);
        builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Intent intent=null;
                //判断手机系统的版本  即API大于10 就是3.0或以上版本 
                if(android.os.Build.VERSION.SDK_INT>10){
                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                }else{
                    intent = new Intent();
                    ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
                    intent.setComponent(component);
                    intent.setAction("android.intent.action.VIEW");
                }
                context.startActivity(intent);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        }).show();
    }
    
    

//	/**
//	 * ListView数据适配器
//	 * @author Administrator
//	 *  
//	 */
//	private class CustomListAdapter extends BaseAdapter implements Filterable, RecyclerListener{
//
//		private LayoutInflater mInflater;
//		public LinkedList<ContactGroup> mList;
//		
//	    private LinkedList<ContactGroup> mOriginalValues;
//	    private final Object mLock = new Object();
//	    private MyFilter myFilter;
//
//		public CustomListAdapter(Context pContext, LinkedList<ContactGroup> pList) {
//			mInflater = LayoutInflater.from(pContext);
//			if(pList != null){
//				mList = pList;
//			}else{
//				mList = new LinkedList<ContactGroup>();
//			}
//		}
//		
//		@Override
//		public int getCount() {
//			return mList.size();
//		}
//
//		@Override
//		public Object getItem(int position) {
//			return mList.get(position);
//		}
//
//		@Override
//		public long getItemId(int position) {
//			return position;
//		}
//		
//        public void addItemLast(List<ContactGroup> datas) {
//        	if(datas!=null){
//        		mList.clear();
//            	for (ContactGroup info : datas) {
//            		mList.add(info);
//                }
//        	}
//        }
//        
//        public int containsKey(String key){
//        	int i = 0;
//        		Iterator<ContactGroup> it = mList.iterator();
//        		ContactGroup di;
//        		while(it.hasNext()){
//        			di = it.next();
//        			
//        		    if(StringUtils.parseBareAddress(di.getJID()).equals(key))
//        		    	return i;
//        		    i++;
//        		}
//        	return -1;
//        }
//
//		@Override
//		public View getView(int position, View convertView, ViewGroup parent) {
//			if (getCount() == 0) {
//				return null;
//			}
//			ViewHolder holder = null;
//			if (convertView == null) {
//				convertView = mInflater.inflate(R.layout.listitem_contacts, null);
//
//				holder = new ViewHolder();
//				holder.imageView = (FlowView)convertView.findViewById(R.id.news_pic);
////				holder.mTitle = (TextView) convertView.findViewById(R.id.news_title);
////				holder.mContent = (TextView) convertView.findViewById(R.id.news_content);
////				holder.mGentie=(TextView) convertView.findViewById(R.id.news_gentiecount);
//				holder.contentView = (HandyTextView) convertView.findViewById(R.id.user_item_htv_name);//昵称
//                holder.user_item_layout_gender = (LinearLayout)convertView.findViewById(R.id.user_item_layout_gender);
//                holder.user_item_iv_gender = (ImageView)convertView.findViewById(R.id.user_item_iv_gender);
//                holder.user_item_htv_age = (HandyTextView)convertView.findViewById(R.id.user_item_htv_age);
//                
//                holder.user_item_htv_account = (HandyTextView)convertView.findViewById(R.id.user_item_htv_account);//帐号
//                holder.user_item_htv_sign = (HandyTextView)convertView.findViewById(R.id.user_item_htv_sign);//个性签名
//                holder.user_item_iv_icon_group_role = (ImageView)convertView.findViewById(R.id.user_item_iv_icon_group_role);
//                holder.user_item_relative = (RelativeLayout)convertView.findViewById(R.id.user_item_relative);
//                holder.badgeView = new BadgeView(mContext, holder.user_item_relative);
//                holder.unreadmsgnumber = (TextView)convertView.findViewById(R.id.unreadmsgnumber);
//				convertView.setTag(holder);
//			} else {
//				holder = (ViewHolder) convertView.getTag();
//			}
//			ContactGroup detail=mList.get(position);
////            holder.mTitle.setText(detail.getTitle());
////            holder.mContent.setText(detail.getContent());
////            holder.mGentie.setText(detail.getGentiecount()+"跟帖");
//			int cgrouptype = detail.getType();////0 contact,1 group
//			switch(cgrouptype){
//				case 0:
//					if(detail.getName()!=null
//							&& !detail.getName().equalsIgnoreCase("null")
//							&& detail.getName().length()!=0)
//						holder.contentView.setText(detail.getName());
//					else
//						holder.contentView.setText(detail.getUsername());
//					holder.imageView.set_url(detail.getAvatarPath());
////					holder.user_item_htv_account.setText(detail.getUsername());
//					holder.user_item_htv_account.setText(StringUtils.parseBareAddress(detail.getJID()));
//		            holder.user_item_htv_sign.setText(detail.getNote());
//		            
//	            	if(detail.getSex()==1){//0 默认未知，1男，2女
//	            		holder.user_item_layout_gender.setBackgroundResource(R.drawable.bg_gender_male);
//	            		holder.user_item_iv_gender.setImageResource(R.drawable.ic_user_male);
//	            	}else{
//	            		holder.user_item_layout_gender.setBackgroundResource(R.drawable.bg_gender_famal);
//	            		holder.user_item_iv_gender.setImageResource(R.drawable.ic_user_famale);
//	            	}
//	            	holder.user_item_iv_icon_group_role.setVisibility(View.GONE);
//	            	int age = 0;
//	                if(detail.getBirthyear()!=null
//	                		&& !detail.getBirthyear().equalsIgnoreCase("null")
//	                		&& detail.getBirthyear().length()!=0
//	                		&& detail.getBirthmonth()!=null
//	                		&& !detail.getBirthmonth().equalsIgnoreCase("null")
//	                		&& detail.getBirthmonth().length()!=0
//	                		&& detail.getBirthday()!=null
//	                		&& !detail.getBirthday().equalsIgnoreCase("null")
//	                		&& detail.getBirthday().length()!=0){
//	                	
//	                	try{
//	                		age = TextUtils.getAge(Integer.parseInt(detail.getBirthyear()),
//	                				Integer.parseInt(detail.getBirthmonth()),
//	                				Integer.parseInt(detail.getBirthday()));
//	                	}catch(Exception e){
//	                		e.printStackTrace();
//	                		age = 0;
//	                	}
//	                }
//	                if(age>200)
//	                	holder.user_item_htv_age.setText("未知");
//	                else
//	                	holder.user_item_htv_age.setText(age+"");
//					break;
//				case 1:
//					if(detail.getTagname()!=null
//							&& !detail.getTagname().equalsIgnoreCase("null")
//							&& detail.getTagname().length()!=0)
//						holder.contentView.setText(detail.getTagname());
//					else
//						holder.contentView.setText(detail.getTagid());
//					holder.imageView.set_url(detail.getPic());
////					holder.user_item_htv_account.setText(detail.getTagid());
//					holder.user_item_htv_account.setText(StringUtils.parseBareAddress(detail.getJID()));
//					if(detail.getSubject()!=null
//							&& !detail.getSubject().equalsIgnoreCase("null")
//							&& detail.getSubject().length()!=0)
//						holder.user_item_htv_sign.setText(detail.getSubject());
//					else
//						holder.user_item_htv_sign.setText("");
//		            holder.user_item_layout_gender.setBackgroundResource(R.drawable.bg_grouplist_ower);
//	        		holder.user_item_iv_gender.setImageResource(R.drawable.ic_userinfo_group4);
//	        		holder.user_item_iv_icon_group_role.setVisibility(View.VISIBLE);
//	        		holder.user_item_htv_age.setText("群组");
//	        		mImageFetcher.loadImage(detail.getPic().replace("localhost", "10.0.2.2"), holder.imageView);
//					break;
//				default:
//					break;
//			}
////			holder.contentView.setText(detail.getName()+detail.getTagname()+detail.getTagid()+detail.getUid());
//            
//            //设置图片
//          /*  try{
//            	File file=new File(Environment.getExternalStorageDirectory()+"/chinanews",detail.getTitle());
//            	if(file.exists()&&file.length()>0){
//            		holder.mImage.setImageURI(Uri.fromFile(file));
//            	}else{
//            		//去下载
//            		Bitmap bitmap=HttpConnect.getImage(detail.getPicpath(), detail.getTitle());
//            		holder.mImage.setImageBitmap(bitmap);
//            	}
//            }catch(Exception e){
//            	
//            }*/
////			mImageFetcher.loadImage(detail.getPic(), holder.imageView);
//            Object num = UnReadMsgNumberMap.get(StringUtils.parseBareAddress(detail.getJID()));
//            int unreadnum = 0;
//            if(num!=null){
//            	try{
//            		unreadnum = Integer.parseInt((String)num);
//            	}catch(Exception e){
//            		unreadnum = 0;
//            	}
//            }
//            if(unreadnum!=0){
//	            holder.badgeView.setText(""+unreadnum);
//	            holder.badgeView.show();
////	            holder.unreadmsgnumber.setVisibility(View.VISIBLE);
////	            holder.unreadmsgnumber.setText(""+unreadnum);
//            }else{
//            	holder.badgeView.hide();
////            	holder.unreadmsgnumber.setVisibility(View.GONE);
//            }
//			return convertView;
//		}
//		
//        /**
//        249	     * 当列表单元滚动到可是区域外时清除掉已记录的图片视图
//        250	     *
//        251	     * @param view
//        252	     */
//        @Override
//        public void onMovedToScrapHeap(View view) {
////        	if(flagType){
//	            ViewHolder holder = (ViewHolder) view.getTag();
//	//        	this.imageViews.remove(holder.avatar);
//	//        	this.imageViews.remove(holder.picPhoto);
//	            if(holder!=null && holder.imageView!=null){
//		            holder.imageView.recycle();
//		            holder.imageView = null;
//	            }
////        	}
//        }
//        
//        @Override
//        public Filter getFilter() {
//           if (myFilter == null) {
//              myFilter = new MyFilter();
//           }
//           return myFilter;
//        }
//        
//        public class MyFilter extends Filter {
//        	 
//            @Override
//            protected FilterResults performFiltering(CharSequence prefix) {
//               // 持有过滤操作完成之后的数据。该数据包括过滤操作之后的数据的值以及数量。 count:数量 values包含过滤操作之后的数据的值
//               FilterResults results = new FilterResults();
//       
//               if (mOriginalValues == null) {
//                  synchronized (mLock) {
//                      // 将list的用户 集合转换给这个原始数据的ArrayList
//                      mOriginalValues = mList;
//                  }
//               }
//               if (prefix == null || prefix.length() == 0) {
//                  synchronized (mLock) {
//                	  LinkedList<ContactGroup> list = mOriginalValues;
//                      results.values = list;
//                      results.count = list.size();
//                  }
//               } else {
//                  // 做正式的筛选
//                  String prefixString = prefix.toString().toLowerCase();
//                  Pattern p = Pattern.compile(prefixString);
//                  // 声明一个临时的集合对象 将原始数据赋给这个临时变量
//                  final LinkedList<ContactGroup> values = mOriginalValues;
//       
//                  final int count = values.size();
//       
//                  // 新的集合对象
//                  final LinkedList<ContactGroup> newValues = new LinkedList<ContactGroup>();
//       
//                  for (int i = 0; i < values.size(); i++) {
//                      // 如果姓名的前缀相符或者电话相符就添加到新的集合
//                      final ContactGroup info = (ContactGroup) values.get(i);
//       
////                      Log.i("coder", "PinyinUtils.getAlpha(value.getUsername())"
////                            + PinyinUtils.getAlpha(value.getUsername()));
////                      if (PinyinUtils.getAlpha(value.getUsername()).startsWith(
////                            prefixString)
////                            || value.getPhonenum().startsWith(prefixString)||value.getUsername().startsWith(prefixString)) {
////       
////                         newValues.add(info);
////                      }
//	      	            Matcher matcher = p.matcher(info.getName()+info.getUsername()+info.getTagname());
//	    	            if(matcher.find()){
//	    	            	newValues.add(info);
//	    	            }
//                  }
//                  // 然后将这个新的集合数据赋给FilterResults对象
//                  results.values = newValues;
//                  results.count = newValues.size();
//               }
//       
//               return results;
//            }
//       
//            @Override
//            protected void publishResults(CharSequence constraint,
//                  FilterResults results) {
//               // 重新将与适配器相关联的List重赋值一下
//            	mList = (LinkedList<ContactGroup>) results.values;
//               if (results.count > 0) {
//                  notifyDataSetChanged();
//               } else {
//                  notifyDataSetInvalidated();
//               }
//            }
//       
//         }
//	}
//	private static class ViewHolder {
//		private FlowView imageView;
////		private TextView mTitle;
////		private TextView mContent;
////		private TextView mGentie;
//		private HandyTextView contentView;
//        TextView timeView;
//        
//        LinearLayout user_item_layout_gender;//20140731 added
//        ImageView user_item_iv_gender;
//        HandyTextView user_item_htv_age;
//        
//        HandyTextView user_item_htv_account;//帐号
//        HandyTextView user_item_htv_sign;//个性签名
//        
//        ImageView user_item_iv_icon_group_role;
//        
//        RelativeLayout user_item_relative;
//        
//        BadgeView badgeView;
//        TextView unreadmsgnumber;
//	}
	
//	   class watcher implements TextWatcher{
//
//	        @Override
//	        public void afterTextChanged(Editable s) {
//	            // TODO Auto-generated method stub
//	            
//	        }
//
//	        @Override
//	        public void beforeTextChanged(CharSequence s, int start, int count,
//	                int after) {
//	            // TODO Auto-generated method stub    
//	            
//	        }
//
//	        @Override
//	        public void onTextChanged(CharSequence s, int start, int before,
//	                int count) {
//	        	mAdapter.getFilter().filter(s.toString());
//	        }
//	        
//	    }
	
	////////////////////////刷新部分数据//////////////////////////////////////
//	private void initRefreshView(LinkedList<ContactGroup> mList){
//		mAdapter = new CustomListAdapter(this, mList);
////		mListView = (CustomListView)this.findViewById(R.id.mListView);
////		mListView.setAdapter(mAdapter);
//////		mListView.setOnClickListener();//
////		mListView.setOnItemClickListener(mOnContactClick);//
////		
//////		CustomListAdapter adapter=maps.get(item);
//////		CustomListView listView=mapList.get(item);
//////		if(adapter==null){
//////			maps.put(item, mAdapter);
//////		}
//////		if(listView==null){
//////			mapList.put(item, mListView);
//////		}
////
////		mListView.setOnRefreshListener(new OnRefreshListener() {
////			@Override
////			public void onRefresh() {
////				getContactList(ConstantValues.refresh);
//////				getContactList();
////			}
////		});
////
////		mListView.setOnLoadListener(new OnLoadMoreListener() {
////			@Override
////			public void onLoadMore() {
////				getContactList(ConstantValues.load);
//////				getContactList();
////			}
////		});
//		
//		ptrlv = (PullToRefreshListView) this.findViewById(R.id.ptrlvHeadLineNews);
//        ptrlv.setOnItemClickListener(mOnContactClick);
////      ptrlv.setOnLongClickListener(mOnContactLongClick);
//        ptrlv.setMode(Mode.BOTH);
//        ptrlv.setOnRefreshListener(new MyOnRefreshListener2());
////      ptrlv.getRefreshableView().setRecyclerListener();
//        ptrlv.setAdapter(mAdapter);
//		
//	}
//	class MyOnRefreshListener2 implements OnRefreshListener2<ListView> {
//
////		private PullToRefreshListView mPtflv;
//
//		public MyOnRefreshListener2() {
////			this.mPtflv = ptflv;
//		}
//
//		@Override
//		public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
//			// 下拉刷新
//			getContactList(ConstantValues.refresh);
//		}
//
//		@Override
//		public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
//			// 上拉加载
//			getContactList(ConstantValues.load);
//		}
//
//	}
	
	
	private Handler mHandler = new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
//				mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
//				mHeaderLayout.setTitleRightImageButton("搜索结果", null,
//						R.drawable.return2,
//						new OnRightImageButtonClickListener());
				mLayoutChat.setVisibility(View.GONE);
				mLayoutReport.setVisibility(View.GONE);
				mLayoutInvite.setVisibility(View.GONE);
				mLayoutFeed.setVisibility(View.GONE);
				user_item_relative.setVisibility(View.GONE);
				account_gone.setVisibility(View.VISIBLE);
				otherprofile_layout_sex_sign.setVisibility(View.GONE);
				otherprofile_bottom.setVisibility(View.GONE);
				//没有获取到数据：可能网络问题
//				Toast.makeText(mContext, "没有获取到数据：可能网络问题", Toast.LENGTH_SHORT).show();
				break;
			case 1:
//				mHeaderLayout.init(HeaderStyle.TITLE_CHAT);
//				mHeaderLayout.setTitleChat(R.drawable.ic_chat_dis_1,
//						R.drawable.bg_chat_dis_active, "搜索结果",
//						"",
//						R.drawable.ic_menu_invite,//ic_menu_invite  ic_topbar_profile
//						new OnMiddleImageButtonClickListener(),
//						R.drawable.return2,
//						new OnRightImageButtonClickListener());
//				mLayoutChat.setVisibility(View.VISIBLE);
//				mLayoutReport.setVisibility(View.VISIBLE);
				mLayoutFeed.setVisibility(View.VISIBLE);
				
				
				//个人动态
				if (mFeeds!=null
						&& mFeeds.size()!=0) {
		        Feed feed = (Feed)mFeeds.get(0);
					mLayoutFeed.setVisibility(View.VISIBLE);
					mHtvFeedSignature.setText(feed.getContent());//mProfile.getSign()
//					if (mProfile.getSignPicture() != null) {//图文混排
						mLayoutFeedPicture.setVisibility(View.VISIBLE);
						String[] imgArray = null;
						String img = feed.getContentImage();
						if(img!=null 
								&& !img.equalsIgnoreCase("null")
								&& img.length()!=0)
//							img = img.substring(0, img.length()-1);
							imgArray = img.split("\\|");
						if(imgArray!=null)
//						mImageFetcher.loadNormalImage(XmppConnectionAdapter.downloadPrefix+StringUtils.parseName(JIDWithRes)+"/"+imgArray[0], mRivFeedPicture,1,40,40,null);
//						ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+"/jeesiteoa/userfiles/"+fuid+"/images/photo/"+imgArray[0], mRivFeedPicture ,SpiceApplication.getInstance().options);
						ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix+"/userfiles/"+fuid+"/images/photo/"+imgArray[0], mRivFeedPicture ,SpiceApplication.getInstance().options);
					mHtvFeedDistance.setText(feed.getSite());//动态发布距离mProfile.getSignDistance()
				} else {
					mLayoutFeed.setVisibility(View.GONE);
				}
				
				user_item_relative.setVisibility(View.VISIBLE);
				account_gone.setVisibility(View.GONE);
				otherprofile_layout_sex_sign.setVisibility(View.VISIBLE);
				otherprofile_bottom.setVisibility(View.VISIBLE);
				
//				ContactGroup detail=(ContactGroup)linkedList.get(0);
				Iterator iter = linkedList.entrySet().iterator();
				Map.Entry entry = null;
				Object key = null;
				Object val = null;
				ContactGroup detail = null;
				while (iter.hasNext()) {
	    			entry = (Map.Entry) iter.next();
	    			key = entry.getKey();
	    			val = entry.getValue();
	    			detail = (ContactGroup)val;
	    			fuid = StringUtils.parseBareAddress2(detail.getJID());
	    			isfriend = key+"";
				}
				if(isfriend!=null && isfriend.equalsIgnoreCase("true")){
					mLayoutChat.setVisibility(View.VISIBLE);
					mLayoutReport.setVisibility(View.VISIBLE);
					mLayoutInvite.setVisibility(View.GONE);
				}else{
					mLayoutChat.setVisibility(View.GONE);
					mLayoutReport.setVisibility(View.GONE);
					mLayoutInvite.setVisibility(View.VISIBLE);
				}
//	            holder.mTitle.setText(detail.getTitle());
//	            holder.mContent.setText(detail.getContent());
//	            holder.mGentie.setText(detail.getGentiecount()+"跟帖");
				if(detail!=null){
				int cgrouptype = detail.getType();////0 contact,1 group
				switch(cgrouptype){
					case 0:
						if(detail.getName()!=null
								&& !detail.getName().equalsIgnoreCase("null")
								&& detail.getName().length()!=0)
							contentView.setText(detail.getName());
						else
							contentView.setText(detail.getUsername());
//						imageView.set_url(detail.getAvatarPath());
//						mImageFetcher.loadImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+detail.getAvatarPath(), imageView);
						mImageFetcher.loadImage(XmppConnectionAdapter.downloadPrefix+detail.getAvatarPath(), imageView);
						user_item_htv_account.setText(StringUtils.parseBareAddress(detail.getJID()));
			            user_item_htv_sign.setText(detail.getNote());
			            
		            	if(detail.getSex()==1){//0 默认未知，1男，2女
		            		user_item_layout_gender.setBackgroundResource(R.drawable.bg_gender_male);
		            		user_item_iv_gender.setImageResource(R.drawable.ic_user_male);
		            	}else{
		            		user_item_layout_gender.setBackgroundResource(R.drawable.bg_gender_famal);
		            		user_item_iv_gender.setImageResource(R.drawable.ic_user_famale);
		            	}
		            	user_item_iv_icon_group_role.setVisibility(View.GONE);
		            	int age = 0;
		                if(detail.getBirthyear()!=null
		                		&& !detail.getBirthyear().equalsIgnoreCase("null")
		                		&& detail.getBirthyear().length()!=0
		                		&& detail.getBirthmonth()!=null
		                		&& !detail.getBirthmonth().equalsIgnoreCase("null")
		                		&& detail.getBirthmonth().length()!=0
		                		&& detail.getBirthday()!=null
		                		&& !detail.getBirthday().equalsIgnoreCase("null")
		                		&& detail.getBirthday().length()!=0){
		                	
		                	try{
		                		age = TextUtils.getAge(Integer.parseInt(detail.getBirthyear()),
		                				Integer.parseInt(detail.getBirthmonth()),
		                				Integer.parseInt(detail.getBirthday()));
		                	}catch(Exception e){
		                		e.printStackTrace();
		                		age = 0;
		                	}
		                }
		                if(age>200)
		                	user_item_htv_age.setText("未知");
		                else
		                	user_item_htv_age.setText(age+"");
						break;
					case 1:
						if(detail.getTagname()!=null
								&& !detail.getTagname().equalsIgnoreCase("null")
								&& detail.getTagname().length()!=0)
							contentView.setText(detail.getTagname());
						else
							contentView.setText(detail.getTagid());
						imageView.set_url(detail.getPic());
						user_item_htv_account.setText(StringUtils.parseBareAddress(detail.getJID()));
						if(detail.getSubject()!=null
								&& !detail.getSubject().equalsIgnoreCase("null")
								&& detail.getSubject().length()!=0)
							user_item_htv_sign.setText(detail.getSubject());
						else
							user_item_htv_sign.setText("");
			            user_item_layout_gender.setBackgroundResource(R.drawable.bg_grouplist_ower);
		        		user_item_iv_gender.setImageResource(R.drawable.ic_userinfo_group4);
		        		user_item_iv_icon_group_role.setVisibility(View.VISIBLE);
		        		user_item_htv_age.setText("群组");
//		        		mImageFetcher.loadImage(detail.getPic().replace("localhost", "10.0.2.2"), imageView);
//		        		mImageFetcher.loadImage(detail.getPic().replace("http://localhost:8080/javacenterhome/", XmppConnectionAdapter.downloadPrefix), imageView);
		        		mImageFetcher.loadImage( XmppConnectionAdapter.downloadPrefix+detail.getPic(), imageView);
						break;
					default:
						break;
				}
				}
				break;
//			case REFRESH_DATA_FINISH:
//				if(mAdapter!=null){
//					List<ContactGroup> newNews=(List<ContactGroup>) msg.obj;
////					for(ContactGroup news :newNews){
////						mAdapter.mList.addFirst(news);
////					}
//					mAdapter.addItemLast(newNews);
//					mAdapter.notifyDataSetChanged();
//				}
////				mListView.onRefreshComplete();	//下拉刷新完成
//				ptrlv.onRefreshComplete();
//				break;
//			case LOAD_DATA_FINISH:
//				if(mAdapter!=null){
////					mAdapter.mList.addAll((LinkedList<ContactGroup>)msg.obj);
//					List<ContactGroup> newNews=(List<ContactGroup>) msg.obj;
//					mAdapter.addItemLast(newNews);
//					mAdapter.notifyDataSetChanged();
//				}
////				mListView.onLoadMoreComplete();	//加载更多完成
//				ptrlv.onRefreshComplete();
//				break;
//			case PIC:
//				mViewPager.setCurrentItem(currentPosition);
//				break;
			case 2:
				showCustomToast(memo);
				break;
			case 3:
				showCustomToast(errorMsg[errorType]);
				break;
			case 4:
//				dialog3.dismiss();
				if(errorType==5)
					showCustomToast("修改更新成功!");
				else
					showCustomToast(errorMsg[errorType]);
				break;
			case 5:
//				dialog3.dismiss();
				showCustomToast(errorMsg[errorType]);
				break;
			case 8:
				if(retcodeProfile.equals("0000"))
					showCustomToast("修改更新成功!");
				else if(memoProfile!=null && memoProfile.length()!=0 && !memoProfile.equalsIgnoreCase("null"))
					showCustomToast(memoProfile);
				else
					showCustomToast(errorMsg[errorType]);
				break;
			default:
				break;
			}
		};
	};
	
//	public void parserData(final int type) {
//		// 去服务器去数据
////		refreshData(type);
//		
//		switch (type) {
////		case 0:
////			initRefreshView(linkedList);
////			break;
//		case 0:
//			Message load0 = mHandler.obtainMessage(LOAD_DATA_FINISH, linkedList);
//			mHandler.sendMessage(load0);
//			break;
//		case 1:
//			Message refresh = mHandler.obtainMessage(REFRESH_DATA_FINISH,
//					linkedList);
//			mHandler.sendMessage(refresh);
//			break;
//		case 2:
//			Message load = mHandler.obtainMessage(LOAD_DATA_FINISH, linkedList);
//			mHandler.sendMessage(load);
//			break;
//
//		default:
//			break;
//		}
//	}
	
	private class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {
	
		@Override
		public void onClick() {
//			getContactList(ConstantValues.refresh);
//			startActivity(new Intent(OtherProfileActivity.this, ContactFrameActivity.class));//ContactListPullRefListActivity
			Intent intent =  new Intent(OtherProfileActivity.this, ContactFrameActivity.class);
	    	intent.putExtra("refreshroster", "true");
			startActivity(intent);
			OtherProfileActivity.this.finish();
		}
	}
	private class OnMiddleImageButtonClickListener implements
	onMiddleImageButtonClickListener {

		@Override
		public void onClick() {
			flag = true;
//			getContactList(ConstantValues.refresh);
//			mBaseDialog = BaseDialog.getDialog(OtherProfileActivity.this, "添加好友", "您确定要添加吗?",
//					"确定", new DialogInterface.OnClickListener() {
//		
//						@Override
//						public void onClick(DialogInterface dialog, int which) {
//							dialog.dismiss();
//							//具体功能操作
//						}
//			},"取消", new DialogInterface.OnClickListener() {
//
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//						dialog.dismiss();;
//				}
//			});
//			mBaseDialog.show();
			
			mEditTextDialog = new EditTextDialog(mContext);
			mEditTextDialog.setTitle("添加好友,填写备注留言");
			mEditTextDialog.setButton("取消",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							mEditTextDialog.cancel();
						}
					}, "确认", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							String text = mEditTextDialog.getText();
							if (text == null) {
								mEditTextDialog.requestFocus();
								showCustomToast("请输入发送给对方的备注留言");
							} else {
								mEditTextDialog.dismiss();
								showCustomToast("您输入的备注留言为:" + text);
								
							}
						}
					});
			mEditTextDialog.show();
		}
	}
	private boolean isWork = false;
	public class OnSwitcherButtonClickListener implements
	onSwitcherButtonClickListener {
	
		@Override
		public void onClick(SwitcherButtonState state) {
			if(!isWork){//20141120防止恶意切换
//				FragmentTransaction ft = getSupportFragmentManager()
//						.beginTransaction();
//				ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
				switch (state) {
				case LEFT:
					
					mHeaderLayout.setDefaultTitle("好友列表",null);
//					ft.replace(R.id.contactframe_layout_content, contactListsFragment).commit();
					break;
			
				case RIGHT:
					mHeaderLayout.setDefaultTitle("招呼盒子",null);
//					ft.replace(R.id.contactframe_layout_content, greetInfosFragment).commit();
					break;
				}
			}
		}

	}
	
	
//    /**
//     * Event simple click on item of the contact list.
//     * 单击某联系人，打开chat聊天对话框
//     */
////    private class BeemContactListOnClick implements PLA_ListView.OnItemClickListener {
//    public class ContactGroupListOnClick implements OnItemClickListener {//private
//		/**
//		 * Constructor.
//		 */
//		public ContactGroupListOnClick( ) {
//		}
//		/**
//		 * {@inheritDoc}
//		 */
//		@Override
//		public void onItemClick(AdapterView<?> arg0, View v, int pos, long lpos) {
//////			ptrlv.getAdapter().getView(pos, v, ptrlv);  
////			ptrlv.getRefreshableView().getAdapter().getView(pos, v, ptrlv); 
////			RelativeLayout user_item_relative = (RelativeLayout)v.findViewById(R.id.user_item_relative);
////			BadgeView badgeView = new BadgeView(mContext, user_item_relative);
////            badgeView.setText("2");
////            badgeView.show();
//////            holder.badgeView.hide();
//            
//			ViewHolder holder = (ViewHolder) v.getTag();
//			if(holder.badgeView.isShown())
//				holder.badgeView.hide();
////			holder.unreadmsgnumber.setVisibility(View.GONE);
//			
//			
//		    ContactGroup c = (ContactGroup)linkedList.get(pos-1);//pos-1
//		    
//		    Toast.makeText(OtherProfileActivity.this, "单击：" + (pos-1), Toast.LENGTH_SHORT).show();
//		    
//		    UnReadMsgNumber unReadMsgNumber = new UnReadMsgNumber();
//		    unReadMsgNumber.setKey(StringUtils.parseBareAddress(c.getJID()));
//		    unReadMsgNumber.setUnreadnumber(0);
//		    duitangInfoAdapter.addUnReadMsgNumber(unReadMsgNumber);
//		    UnReadMsgNumberMap.put(StringUtils.parseBareAddress(c.getJID()), ""+0);
////		    
////		    
//		    Intent i = new Intent(OtherProfileActivity.this,ChatPullRefListActivity.class);
////		    i.setData(c.getUuid());
////            if(c.getAvatarId()!=null 
////            		&& c.getAvatarId().length()!=0 
////            		&& !c.getAvatarId().equalsIgnoreCase("null")
////            		&& (
////            				c.getAvatarId().toLowerCase().endsWith(".jpg")
////            				|| c.getAvatarId().toLowerCase().endsWith(".png")
////            				|| c.getAvatarId().toLowerCase().endsWith(".bmp")
////            				|| c.getAvatarId().toLowerCase().endsWith(".gif")
////            			)
////            		&& c.getJIDWithRes().indexOf("@conference.")==-1)
////            	i.putExtra("headimg", XmppConnectionAdapter.downloadPrefix+StringUtils.parseName(c.getJIDWithRes())+"/"+c.getAvatarId());//+"thumbnail_"
////		    i.putExtra("myheadimg", myheadimg);
////		    i.putExtra("username",c.getName());
////		    i.putExtra("myusername",myusername);
//		    int type = c.getType();//0 contact,1 group
//		    i.putExtra("type", type);
//		    i.putExtra("uid", c.getUid());
//		    i.putExtra("uuid", c.getUuid());
//		    i.putExtra("username", c.getUsername());
//		    i.putExtra("name", c.getName());
//		    i.putExtra("avatarpath", c.getAvatarPath());
//		    
//		    i.putExtra("tagid", c.getTagid());
//		    i.putExtra("tagname", c.getTagname());
//		    i.putExtra("pic", c.getPic());//群组头像pic
//		    i.putExtra("jid", c.getJID());
//            startActivity(i);
//		}
//    }
	
	
	private void addFriendRequest(final String fuid,final String note) {
//		private View view2;
//		private int type2;
		if(!isWork){
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				loadingDialog.show();
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				return initAddFriend(fuid,note);
//				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				loadingDialog.dismiss();
//				if (result) {	
					if(retcode!=null 
							&& !retcode.equalsIgnoreCase("null")
							&& retcode.length()!=0)
						mHandler.sendEmptyMessage(2);
					else
						mHandler.sendEmptyMessage(3);
//					showCustomToast("操作成功");
//				}else{
//					//提示没有获取到数据：可能网络问题
//					mHandler.sendEmptyMessage(3);
//				}
				isWork = false;
			}

		});
		isWork = true;
		}
	}
	private String retcode = "";
	private String memo = "";
	public boolean initAddFriend(String fuid,String note){
		if(BeemConnectivity.isConnected( getApplicationContext())){
		    try {
		    	if(mXmppFacade!=null){
			    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
			    			){
			    		
			    		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
			    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
			    	    
			    		FriendAddIQ reqXML = new FriendAddIQ();
			            reqXML.setId("1234567890");
			            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
			            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
			            reqXML.setUsername(username);
			            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
			            reqXML.setUuid(uuid);
			            reqXML.setFuid(fuid);
			            reqXML.setNote(note);
			            reqXML.setOp("add");
//			            String hashcode = "";//apikey+uid+fuid 使用登录成功后返回的sessionid作为密码做3des运算
			            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+fuid;
			            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
			            reqXML.setHashcode(hash_dest);
			            reqXML.setType(IQ.Type.SET);
			            String elementName = "friendaddiq"; 
			    		String namespace = "com:isharemessage:friendaddiq";
			    		FriendAddIQResponseProvider provider = new FriendAddIQResponseProvider();
			            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "friendaddiq", "com:isharemessage:friendaddiq", provider);
			            
			            if(rt!=null){
			                if (rt instanceof FriendAddIQResponse) {
			                	final FriendAddIQResponse friendAddIQResponse = (FriendAddIQResponse) rt;

			                    if (friendAddIQResponse.getChildElementXML().contains(
			                            "com:isharemessage:friendaddiq")) {
//			    					MainActivity.this.runOnUiThread(new Runnable() {
//				                    	
//            							@Override
//            							public void run() {
//            								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
//            							}
//            						});
			                        String Id = friendAddIQResponse.getId();
			                        String Apikey = friendAddIQResponse.getApikey();
			                        String recode = friendAddIQResponse.getRetcode();
			                        retcode = recode;
			                        memo = friendAddIQResponse.getMemo();
			                        if(recode.equalsIgnoreCase("0000")){
			                        	errorType = 5;
				                        return true;
			                        }else{
			                        	errorType = 6;
			                        	return false;
			                        }
			                        	
			                    }
			                } 
			            }
			    		
						mBinded = true;//20130804 added by allen
			    	}else
			    		errorType = 1;
		    	}else
		    		errorType = 2;
				
		    } catch (RemoteException e) {
		    	errorType = 3;
		    	e.printStackTrace();
		    	
		    } catch (Exception e){
		    	errorType = 3;
		    	e.printStackTrace();
		    }
	    }else{
	    	errorType = 4;
	    }
		return false;
	}
	
	private void updateProfileRequest(final String name,
			final String gender,///默认0未知，1男，2女
			final String usersign,
			final String birthyear,
			final String birthmonth,
			final String birthday) {
//		private View view2;
//		private int type2;
		if(!isWork){
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				loadingDialog.show();
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				return initUpdateProfile(name,
						gender,///默认0未知，1男，2女
						usersign,
						birthyear,
						birthmonth,
						birthday);
//				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				loadingDialog.dismiss();
////				if (result) {	
//					if(retcode!=null 
//							&& !retcode.equalsIgnoreCase("null")
//							&& retcode.length()!=0)
						mHandler.sendEmptyMessage(8);
//					else
//						mHandler.sendEmptyMessage(5);
////					showCustomToast("操作成功");
////				}else{
////					//提示没有获取到数据：可能网络问题
////					mHandler.sendEmptyMessage(3);
////				}
				isWork = false;
			}

		});
		isWork = true;
		}
	}
	
	String retcodeProfile = "";
	String memoProfile = "";
	public boolean initUpdateProfile(String name,
			String gender,///默认0未知，1男，2女
			String usersign,
			String birthyear,
			String birthmonth,
			String birthday){
		if(BeemConnectivity.isConnected( getApplicationContext())){
		    try {
		    	if(mXmppFacade!=null){
			    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
			    			){
			    		
			    		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
			    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
			    	    
			    	    UpProfileIQ reqXML = new UpProfileIQ();
			            reqXML.setId("1234567890");
			            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
			            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
			            reqXML.setLogin_name(username);
			            reqXML.setName(name);
			            reqXML.setNote(usersign);
			            reqXML.setSex(gender);
			            reqXML.setBirthyear(birthyear);
			            reqXML.setBirthmonth(birthmonth);
			            reqXML.setBirthday(birthday);
			            
			            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
			            reqXML.setUuid(uuid);
//			            String hashcode = "";//apikey+uid+fuid 使用登录成功后返回的sessionid作为密码做3des运算
			            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid;
			            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
			            reqXML.setHashcode(hash_dest);
			            reqXML.setType(IQ.Type.SET);
			            String elementName = "updateprofileiq"; 
			    		String namespace = "com:isharemessage:updateprofileiq";
			    		UpProfileIQResponseProvider provider = new UpProfileIQResponseProvider();
			            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "updateprofileiq", "com:isharemessage:updateprofileiq", provider);
			            
			            if(rt!=null){
			                if (rt instanceof UpProfileIQResponse) {
			                	final UpProfileIQResponse upProfileIQResponse = (UpProfileIQResponse) rt;

			                    if (upProfileIQResponse.getChildElementXML().contains(
			                            "com:isharemessage:updateprofileiq")) {
//			    					OtherProfileActivity.this.runOnUiThread(new Runnable() {
//				                    	
//            							@Override
//            							public void run() {
//            								showCustomToast("服务器应答消息："+upProfileIQResponse.toXML().toString());
//            							}
//            						});
			                        String Id = upProfileIQResponse.getId();
			                        String Apikey = upProfileIQResponse.getApikey();
			                        String recode = upProfileIQResponse.getRetcode();
			                        retcodeProfile = recode;
			                        memoProfile = upProfileIQResponse.getMemo();
//			                        showCustomToast("000retcode="+retcode+";memo="+memo);
//			    					OtherProfileActivity.this.runOnUiThread(new Runnable() {
//				                    	
//	        							@Override
//	        							public void run() {
//	        								showCustomToast("服务器应答消息："+"000retcode="+retcode+";memo="+memo);
//	        							}
//	        						});
			                        if(recode.equalsIgnoreCase("0000")){
			                        	errorType = 5;
				                        return true;
			                        }else{
			                        	errorType = 6;
			                        	return false;
			                        }
			                        	
			                    }
			                } 
			            }
			    		
						mBinded = true;//20130804 added by allen
			    	}else
			    		errorType = 1;
		    	}else
		    		errorType = 2;
				
		    } catch (RemoteException e) {
		    	errorType = 3;
		    	e.printStackTrace();
		    	
		    } catch (Exception e){
		    	errorType = 3;
		    	e.printStackTrace();
		    }
	    }else{
	    	errorType = 4;
	    }
		return false;
	}
	
	
	private List<DynamicsItem> results = null;
	private DynamicsItem dynamicsItem = null;
	private Feed feed = null;
	private int CTTotal = 0;//总条数
	private int totalnumber = 0;//本次查询返回条数
	
    private int pageCount = 0;//总页数
    
	private List<Feed> mFeeds = new ArrayList<Feed>();
	public void clearComments(){
		mFeeds.clear();
    }
    public void addItem(List<Feed> datas) {
    	if(datas!=null){
//    		mComments.clear();
        	for (Feed info : datas) {
        		mFeeds.add(info);
            }
    	}
    }
    
	public boolean InitialFeeds(String fuid){
//		Log.e("MMMMMMMMMMMM20140828OtherFeedListActivityMMMMMMMMMMMM", "++++++++++++++InitialFeeds="+otherusername);
		if(BeemConnectivity.isConnected(getApplicationContext())){
		    try {
		    	if(mXmppFacade!=null){
			    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()){
//			    		Log.e("MMMMMMMMMMMM20140828OtherFeedListActivityMMMMMMMMMMMM", "++++++++++++++InitialFeeds1 otherusername="+otherusername);
			    		String mtype = "2";
			    		String dynamicid = "";
//			    		username2 = StringUtils.parseName(mXmppFacade.getXmppConnectionAdapter().getUserInfo().getJid());
//			    		Log.e("MMMMMMMMMMMM20140828OtherFeedListActivityMMMMMMMMMMMM", "++++++++++++++InitialFeeds1 username2="+username2);
////			    		String username = "";
			    		String otherusername = fuid;
			    		String longitude = String.valueOf(SpiceApplication.getInstance().mLongitude);
			    		String latitude = String.valueOf(SpiceApplication.getInstance().mLatitude);
			    		String memo = "";
			    		String str_pictures = "";
			    		String str_faner = "";
//			    		String time = com.stb.isharemessage.utils.TextUtils.dateToMillis(new Date());
			    		String time = "";
//			    		String geolocation = BeemApplication.getInstance().mGpsAddr;
			    		String geolocation = "";
//			    		int startIndex = 0;
//			    		int numResults = 100;
//			    		myHashMap = mXmppFacade.getDynamicsItems(mtype,
//			    	    		dynamicid,
//			    	    		username2,
//			    	    		otherusername,
//			    	    		longitude,
//			    	    		latitude,
//			    	    		memo,
//			    	    		str_pictures,
//			    	    		str_faner,
//			    	    		time,
//			    	    		geolocation,
//			    	    		currentPage*numberresult,//startIndex
//			    	    		numberresult);//numResults
//			    		hashMap = myHashMap.getMap();
//			    		Set set = hashMap.entrySet() ;
//			    		java.util.Iterator it = hashMap.entrySet().iterator();
//			    		while(it.hasNext()){
//				    		java.util.Map.Entry entry = (java.util.Map.Entry)it.next();
//				    		CTTotal = Integer.parseInt((String)entry.getKey());// 返回与此项对应的键
//				    		results = (List<DynamicsItemParcelable>)entry.getValue(); //返回与此项对应的值
//				    		
//				    		pageCount = CTTotal%numberresult==0? CTTotal/numberresult-1 : CTTotal/numberresult;
//	                        //System.out.println(entry.getValue());
//			    		} 
//			    		totalnumber = myHashMap.getTotalnumber();
//			    		Log.e("MMMMMMMMMMMM20140828OtherFeedListActivityMMMMMMMMMMMM", "++++++++++++++CTTotal="+CTTotal);
//			    		Log.e("MMMMMMMMMMMM20140828OtherFeedListActivityMMMMMMMMMMMM", "++++++++++++++totalnumber="+totalnumber);
//			    		if(results!=null && results.size()!=0){
//			    			errorType = 5;
//			    			for(int i=0;i<results.size();i++){
//			    				dynamicsItemParcelable = (DynamicsItemParcelable)results.get(i);
//			    				feed = new Feed(dynamicsItemParcelable.getId()+"","",dynamicsItemParcelable.getTime(), 
//			    						dynamicsItemParcelable.getMemo(), 
//			    						dynamicsItemParcelable.getPictures(),
//			    						dynamicsItemParcelable.getFaner(), 
//			    						dynamicsItemParcelable.getDistance(),
//										3,//commentCount
//										dynamicsItemParcelable.getEmail(),
//										dynamicsItemParcelable.getName(),
//										dynamicsItemParcelable.getUid());
//			    				mFeeds.add(feed);
//			    			}
//			    		}else{
//			    			if(results!=null && results.size()==0)
//			    				errorType = 0;
//			    			else
//			    				errorType = 6;
//			    		}
//			    		Log.e("MMMMMMMMMMMM20140828OtherFeedListActivityMMMMMMMMMMMM", "++++++++++++++mFeeds.size()="+mFeeds.size());
			    	    DynamicsIQ reqXML = new DynamicsIQ();
			            reqXML.setId("1234567890");
			            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
			            reqXML.setMtype(mtype);
			            reqXML.setDynamicid(dynamicid);
			            reqXML.setUsername(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
			            reqXML.setOtherusername(otherusername);
			            reqXML.setLongitude(longitude);
			            reqXML.setLatitude(latitude);
			            reqXML.setMemo(memo);
			            reqXML.setPictures(str_pictures);
			            reqXML.setFaner(str_faner);
			            reqXML.setTime(time);
			            reqXML.setGeolocation(geolocation);
			            reqXML.setRadius(5000*1000+"");
			            reqXML.setStartIndex(currentPage*numberresult+"");
			            reqXML.setNumResults(numberresult+"");
			            
			            
			            
			            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
			    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");

			            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
//			            reqXML.setUuid(uuid);
		//	            String hashcode = "";//apikey+username(uid)+time 使用登录成功后返回的sessionid作为密码做3des运算
			            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+time;
			            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
			            reqXML.setHashcode(hash_dest);
			            reqXML.setType(IQ.Type.SET);
			            String elementName = "dynamicsiq"; 
			    		String namespace = "com:stb:dynamicsiq";
			    		DynamicsIQResponseProvider provider = new DynamicsIQResponseProvider();
			            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "dynamicsiq", "com:stb:dynamicsiq", provider);
			            
			            if(rt!=null){
			                if (rt instanceof DynamicsIQResponse) {
			                	final DynamicsIQResponse dynamicsIQResponse = (DynamicsIQResponse) rt;
		
			                    if (dynamicsIQResponse.getChildElementXML().contains(
			                            "com:stb:dynamicsiq")) {
		//	    					MainActivity.this.runOnUiThread(new Runnable() {
		//		                    	
		//    							@Override
		//    							public void run() {
		//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
		//    							}
		//    						});
			                        String Id = dynamicsIQResponse.getId();
			                        String Apikey = dynamicsIQResponse.getApikey();
			                        try{
			                        	CTTotal = Integer.parseInt(dynamicsIQResponse.getCttotal());
			                        	totalnumber = Integer.parseInt(dynamicsIQResponse.getTotalnumber());
			                        	pageCount = CTTotal%numberresult==0? CTTotal/numberresult-1 : CTTotal/numberresult;
			                        }catch(Exception e){
			                        	CTTotal = 0;
			                        	totalnumber = 0;
			                        }
			                        results = dynamicsIQResponse.getDynamics();
						    		if(results!=null && results.size()!=0){
						    			errorType = 5;
						    			for(int i=0;i<1;i++){//results.size()
						    				dynamicsItem = (DynamicsItem)results.get(i);
						    				feed = new Feed(dynamicsItem.getId()+"","",dynamicsItem.getTime(), 
						    						dynamicsItem.getMemo(), 
						    						dynamicsItem.getPictures(),
						    						dynamicsItem.getFaner(), 
						    						dynamicsItem.getDistance(),
													3,//commentCount
													dynamicsItem.getEmail(),
													dynamicsItem.getName(),
													dynamicsItem.getUser_id());
						    				
						    				mFeeds.add(feed);
//						    				mFeeds_temp.add(feed);
						    			}
						    			return true;
						    		}else{
						    			if(results!=null && results.size()==0)
						    				errorType = 0;
						    			else
						    				errorType = 6;
						    		}
			                    }
			                }
			            }
			    	}else
			    		errorType = 1;
		    	}else
		    		errorType = 2;
		    	
		    }catch (RemoteException e) {
		    	errorType = 3;
		    	e.printStackTrace();
		    	
		    } catch (Exception e){
		    	errorType = 3;
		    	e.printStackTrace();
		    }
		    return true;
		}else{
	    	errorType = 4;
	    }
		return false;
	}

}
